package pl.un4giv3n.mightvsmagic.admin.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.action.PersistenceAction;
import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.entity.UserType;
import pl.un4giv3n.mightvsmagic.utils.wrappers.UserActivityWrapper;

/**
 * @author andrzejewskia
 */
public class ListBanPlayerPageAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	/**
	 * session user
	 */
	private User sessionAdmin;
	private long userId;
	private List<UserActivityWrapper> userActivities = new ArrayList<UserActivityWrapper>();
	private String username;
	
	@SuppressWarnings("unchecked")
	@Override
	public String execute() {
		EntityManager em = getEntityManager();
		sessionAdmin = getSessionUser(em);
		if (sessionAdmin == null
				|| sessionAdmin.getUserType() != UserType.ADMIN) {
			addActionError("Zaloguj się");
			em.close();
			return LOGIN;
		}
		User user = em.find(User.class, userId);
		if (user == null) {
			addActionError("Niepoprawny id usera");
			em.close();
			return ERROR;
		}
		username = user.getLogin();
		Query query = em.createNamedQuery("find.activities.older.than");
		query.setParameter("userId", userId);
		query.setParameter("time", System.currentTimeMillis() - ONE_WEEK);
		List<UserActivity> activities = query.getResultList();
		for (Iterator<UserActivity> iterator = activities.iterator(); iterator.hasNext();) {
			UserActivity activity = iterator.next();
			ActivityType activityType = activity.getActivityType();
			if(activityType != ActivityType.ADMIN_BAN_PLAYER && activityType != ActivityType.ADMIN_UNBAN_PLAYER){
				iterator.remove();
			}
		}
		Collections.sort(activities, new Comparator<UserActivity>() {

			@Override
			public int compare(UserActivity o1, UserActivity o2) {
				long o1time = o1.getTimeDone();
				long o2time = o2.getTimeDone();
				return (o1time < o2time ? 1 : (o1time == o2time ? 0 : -1));
			}

		});
		for (int i = 0; i < activities.size(); i++) {
			userActivities.add(toWrapper(activities.get(i)));
		}
		em.close();
		return SUCCESS;
	}

	private UserActivityWrapper toWrapper(UserActivity currentActivity) {
		UserActivityWrapper wrapper = new UserActivityWrapper(currentActivity, "");
		return wrapper;
	}

	public long getUserId() {
		return userId;
	}

	public void setUserId(long userId) {
		this.userId = userId;
	}

	public List<UserActivityWrapper> getUserActivities() {
		return userActivities;
	}

	public String getUsername() {
		return username;
	}

}
